//模拟实现BlockingQueue - 使用环形数组模拟实现 - 浪费一个字节
public class Demo_BlockingQueue {
    //有一个数据结构存数据 - 比如String
    private String[] data = new String[10];
    //队首元素的下标
    private int head = 0;
    //队尾元素的下一个下标
    private int tail = 0;
    //生产者放数据
    public void put(String s){
        try{
            synchronized (this){
                //放之前要先判断满不满
                int index = (tail + 1) % data.length;
                if(index == head){
                    //满了要阻塞等待
                    this.wait();
                }
                data[tail++] = s;
                tail %= data.length;
                this.notify();
            }
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
    public String take(){
        String ret = null;
        try{
            synchronized (this){
                //取元素要先判断空不空
                if(head == tail){
                    //阻塞等待
                    this.wait();
                }
                ret = data[head++];
                head %= data.length;
                this.notify();
            }
        }catch(InterruptedException e){
            e.printStackTrace();
        }
        return ret;
    }
}

class BlockingQueueTest{
    public static void main(String[] args) {
        Demo_BlockingQueue queue = new Demo_BlockingQueue();
        Thread t1 = new Thread(() -> {
            while(true){
                String s = queue.take();
                System.out.println("consumer: " + s);

            }
        }, "consumer");
        Thread t2 = new Thread(() -> {
            int count = 1;
            while(true){
                queue.put("" + count);
                System.out.println("producer: " + count);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                count++;
            }
        }, "producer");
        t1.start();
        t2.start();
    }
}
